package com.sunk.mybatis.plug;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;

import java.lang.reflect.Proxy;
import java.sql.Statement;
import java.util.Properties;

/**
 * @Auther: Sunk
 * @Date: 2019/2/11 15:49
 * @Description:
 */

/**
 * 通过注解来标识当前插件拦截哪个对象的哪个方法
 */
@Intercepts({@Signature(
        type = StatementHandler.class,method = "parameterize",args = Statement.class
)})
public class MyFirstPlugin implements Interceptor {
    /**
     * 拦截目标对象的目标方法执行
     * @param invocation
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //执行目标方法
        System.out.println("intercept:"+invocation.getMethod());
        //动态改变运行参数
        //拿到StatementHandler==>ParameterHandler===>parameterObject
        //拿到目标对象的原数据
        MetaObject metaObject = SystemMetaObject.forObject(invocation.getTarget());
        Object value = metaObject.getValue("parameterHandler.parameterObject");
        System.out.println(value);
        metaObject.setValue("parameterHandler.parameterObject",2);
        Object proceed = invocation.proceed();
        //返回执行后的返回值
        return proceed;
    }

    /**
     *  包装目标对象：包装：为目标对象创建一个代理对象
     * @param o
     * @return
     */
    @Override
    public Object plugin(Object o) {
        //借助Plugin的wrap方法来使用当前拦截器包装目标对象
        System.out.println("plugin:"+o);
        Object wrap = Plugin.wrap(o, this);
        //返回为当前对象创建的代理对象
        return wrap;
    }

    /**
     *  将插件注册时的properties的属性设置进来
     * @param properties
     */
    @Override
    public void setProperties(Properties properties) {
        System.out.println("插件配置信息:"+properties);
    }
}
